package igloo.controller;

import igloo.Application;
import igloo.aws.IglooGlacierClient;
import igloo.model.Job;
import igloo.model.Job.State;

import java.util.Timer;
import java.util.TimerTask;

import com.amazonaws.services.glacier.model.DescribeJobRequest;
import com.amazonaws.services.glacier.model.DescribeJobResult;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;

public class JobController
{
    private final IglooController mIglooController;
    private final Job mJob;
    private Timer mTimer;

    public JobController(IglooController iglooController, Job job)
    {
        mIglooController = iglooController;
        mJob = job;

        if(mJob.getState() != State.Succeeded)
        {
            mTimer = new Timer();
            mTimer.scheduleAtFixedRate(new TimerTask() {
                @Override
                public void run()
                {
                    poll();
                }

            }, 100, 60000);
        }
    }

    public Job getJob()
    {
        return mJob;
    }

    public void poll()
    {
        DescribeJobRequest request = new DescribeJobRequest();
        request.setJobId(mJob.getId());
        request.setVaultName(mJob.getVault().getName());

        IglooGlacierClient glacier = Application.getInstance().getGlacierClient(mJob.getVault()
                                                                                    .getRegion());
        ListenableFuture<DescribeJobResult> future = glacier.describeJob(request);
        Futures.addCallback(future, new FutureCallback<DescribeJobResult>() {
            @Override
            public void onSuccess(DescribeJobResult result)
            {
                mJob.setState(State.valueOf(result.getStatusCode()));
                if(mJob.isComplete())
                {
                    mIglooController.deleteJob(mJob);
                    mTimer.cancel();
                }
            }

            @Override
            public void onFailure(Throwable t)
            {
                t.printStackTrace();
            }
        }, Application.getInstance().getExecutor());
    }
}
